package cn.aaalei.controller;

import cn.aaalei.service.ActionService;
import cn.aaalei.utils.Result;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

@RestController
public class RegisterController {

    @Autowired
    private ActionService actionService;


    @PostMapping("/register")
    public Result register(@RequestBody Map<String,String> requestMap)throws Exception{

        if(actionService.checkUserExists(requestMap.get("username"))){
            return Result.error("要注册的用户名已存在.");
        }
        if (actionService.checkWisdomExists(requestMap.get("wisdomUsername"))){
            return Result.error("要注册的悠学派账号已存在.");
        }
        String res = actionService.login(requestMap.get("wisdomUsername"),requestMap.get("wisdomPassword"));
        if(!JSONObject.parseObject(res).get("code").toString().equals("0")){
            return Result.error("悠学派账号或密码错误.");
        }

        //保存账号到数据库
        if(!actionService.register(requestMap)){
            return Result.error("保存时发生异常.");
        }

        if (!requestMap.get("recommendUsername").equals("")){
            actionService.addRecommendLog(requestMap.get("recommendUsername"),requestMap.get("username"));
        }

        Result result = new Result();
        result.put("username",requestMap.get("username"));
        return result;
    }
}
